<template>
  <div id="userCenter">
    <van-nav-bar :title="'个人资料'"
                 :fixed=true
                 :border=false
                 @click-left="onClickLeft"
                 left-arrow
                 style="height:2.5rem;color: #FFFFFF" />
    <div class="icon">
      <van-cell-group>
        <van-cell></van-cell>
        <van-cell></van-cell>
        <van-cell>
          <van-row type="flex" justify="space-between" align="center">
            <van-col span="6">
              <van-image
                  round
                  width="5rem"
                  height="5rem"
                  :src="getHeadPic"
              ></van-image>
            </van-col>

            <van-col span="6">
              <van-uploader :after-read="uploadFile">
                <van-button icon="plus" plain  type="info" size="small">修改头像</van-button>
              </van-uploader>
            </van-col>
          </van-row>
        </van-cell>
      </van-cell-group>

      <van-form @submit="onSubmit">
        <van-field
            v-model="userInfo.username"
            name="username"
            label="用户名"
            placeholder="用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
            v-model="userInfo.nickname"
            name="nickname"
            label="昵称"
            placeholder="昵称"
            :rules="[{ required: true, message: '请填写昵称' }]"
        />
        <van-field
            name="email"
            v-model="userInfo.email"
            label="邮箱"
        />
        <van-field
            name="phone"
            v-model="userInfo.phone"
            label="手机号"
        />
        <van-field name="gender" label="性别">
          <template #input>
            <van-radio-group v-model="userInfo.gender" direction="horizontal">
              <van-radio name="0">女</van-radio>
              <van-radio name="1">男</van-radio>
              <van-radio name="2">保密</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <div style="margin: 16px;">
          <van-button  block type="info" native-type="submit" size="small">保存信息</van-button>
        </div>
      </van-form>

      <van-form ref="pwdForm" v-show="!passwordFlag" @submit="updatePassword">
        <van-field name="oldPassword"
                   label="原始密码"
                   v-model="oldPassword"
                   type="password"
                   placeholder="请输入密码"
                   :rules="[{ required: true, message: '请填写原始密码' }]">
        </van-field>
        <van-field v-model="password"
                   type="password"
                   name="password" label="新密码"
                   placeholder="请输入新密码"
                   :rules="[{ validator:passwordCheck, message: '新密码长度必须为6至20位的数字和字母组成' }]"
        >
        </van-field>
        <div style="margin: 16px;" v-show="!passwordFlag" >
          <van-button  block type="warning" size="small" @click="updatePassword">保存密码</van-button>
          <van-button  native-type="button" block type="info" size="small" @click="showPassword">取消修改</van-button>
        </div>
      </van-form>
      <div style="margin: 16px;" >
        <van-button v-show="passwordFlag"  block type="warning" size="small" @click="showPassword">修改密码</van-button>
      </div>
      <div style="margin: 16px;" >
        <van-button  block type="danger" size="small" @click="userLogout">退出登录</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import {getJwtToken} from "@/lib/utils/TokenUtil";
import store from "@/store";
import {updateUser, userUpdatePassword} from "@/api/user";
import {logout} from "@/api/system";
import axios from "axios";


export default {
  name: "UserCenter",
  beforeRouteEnter (to,from,next) {
    if (getJwtToken()!==''){
      if (store.state.user.isGetInfo){
        next(vm =>vm.setUserInfo(store.state.user.info))
      }else {
        console.log('Mine:beforeRouteEnter:GetUserInfo')
        store.dispatch('GetUserInfo').then(res=>{
          next(vm =>vm.setUserInfo(res.data))
        })
      }
    }else{
      next()
    }
  },
  data(){
    return{
      userInfo:{},
      fileList:[],
      passwordFlag:true,
      password:'',
      oldPassword:''
    }
  },
  methods:{
    setUserInfo(data){
      this.userInfo = data
      this.userInfo['token'] = getJwtToken()
    },
    // 修改头像
    uploadFile(upFile){
      console.log(upFile);
      let formData = new FormData(); //构造一个 FormData，把后台需要发送的参数添加
      formData.append("file", upFile.file); //接口需要传的参数
      console.log(formData)
      axios.post(store.getters.getStaticValue('BACKEND_URL')+"/user/uploadUserPic",
      formData,
          {
            headers: {
              "content-type": "multer/form-data",
              "AccessToken": getJwtToken()
            },
          }).then(res=>{
        console.log(res);
        this.userInfo.headPic = res.data.data.thumbUrl
        store.commit("setIsGetInfo")
      }).catch(err=>{
        this.$toast.fail({
          message:`${err}`
        })
      })
    },
    // 返回
    onClickLeft () {
      this.$router.back();
    },
    onSubmit(values){
      console.log(this.userInfo)
      let submitData = values
      submitData['userId'] = this.userInfo.userId
      console.log(submitData)
      updateUser(submitData).then(res=>{
        this.$toast.success({
          message:`${res.data}`
        })
      })
    },
    passwordCheck(value){
      return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/.test(value)
    },
    showPassword(){
      this.passwordFlag = !this.passwordFlag
      this.password = ''
      this.oldPassword = ''
      this.$refs['pwdForm'].resetValidation()
    },
    userLogout(){
      logout().then(()=>{
        this.$store.commit("setIsGetInfo");
        this.$router.back();
        sessionStorage.clear() //sessionStorage数据清理
      }).catch(err =>{
        this.$toast.fail({
          message:`${err.message}`
        })
      })
    },
    updatePassword(values){
      let submitData = values
      submitData['userId'] = this.userInfo.userId
      console.log(submitData)
      userUpdatePassword(submitData).then(res=>{
        this.$toast.success({
          message:`${res.data}`
        })
        this.passwordFlag = !this.passwordFlag
      }).catch(err=>{
        this.$toast.fail({
          message:`${err.message}`
        })
      })
    },
  },
  computed:{
    getHeadPic(){
      return this.$store.getters.getStaticValue('BASE_URL_USER_HEAD')+this.userInfo.headPic
    },
  },
}
</script>

<style scoped>

</style>
